﻿using CoreEx.DynamicInvoker;
using LinFu.AOP.Interfaces;

namespace CoreEx.ServiceModel.Implementation
{
    /// <summary>
    /// Intercepts calls made to a service contract proxy type and 
    /// forwards each method call to the actual service instance.
    /// </summary>
    public class ServiceContractInterceptor : IInterceptor
    {
        private readonly object _target;

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceContractInterceptor"/> class.
        /// </summary>
        /// <param name="target">The actual service instance.</param>
        public ServiceContractInterceptor(object target)
        {
            _target = target;
        }

        /// <summary>
        /// Intercepts a method call using the given
        /// <see cref="T:LinFu.AOP.Interfaces.IInvocationInfo"/> instance.
        /// </summary>
        /// <param name="info">The <see cref="T:LinFu.AOP.Interfaces.IInvocationInfo"/> instance that will
        /// contain all the necessary information associated with a
        /// particular method call.</param>
        /// <returns>
        /// The return value of the target method. If the return type of the target
        /// method is <see cref="T:System.Void"/>, then the return value will be ignored.
        /// </returns>
        public object Intercept(IInvocationInfo info)
        {
            //var result = _target.GetType().DynamicInvoke(_target, info.TargetMethod.Name, info.Arguments);
            var result = info.TargetMethod.DynamicInvoke(_target, info.Arguments);
            return result;
        }
    }
}
